#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import configparser
import functools
import os
import itertools
from datetime import datetime, timezone

from common.logger import Logger
from saphanay.resource.saphana import SAPHANA
from saphanay.comm.constants import SAPHANADirectoryStructure
from saphanay.comm.error_code_exception import ErrorCodeException
from saphanay.comm.constants import SAPHANAErrorCode
from saphanay.comm.common_utils import remove_paths, run_subprocess

logger = Logger().get_logger()


class RestoreSAPHANA(SAPHANA):

    """恢复能力 SAP HANA"""

    def __init__(self, sid: str, db_name: str, db_port: str, db_user: str, db_pwd: str) -> None:
        super().__init__(sid, db_name, db_port, db_user, db_pwd)

    @staticmethod
    def timestamp_to_utc_time(timestamp: int) -> str:
        """将 Unix 时间戳转换成 UTC 日期时间。"""
        utc_time = datetime.fromtimestamp(timestamp, tz=timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
        logger.info(f"timestamp {timestamp} -> utc time {utc_time}")
        return utc_time

    def list_required_backups(self, catalog_dir: str, target_time: str, ignore_delta: bool = False) -> list[str]:
        """
        列举出恢复所需的备份文件名。
        :raise ErrorCodeException:
        """
        command = (f'hdbbackupdiag -f -d "{catalog_dir}" -u "{target_time}" --databaseName {self._db_name.upper()}' +
                   " --ignoreDeltaDataBackups" * ignore_delta)
        command = f"su - {self._sid.lower()}adm -c '{command}'"
        process = run_subprocess(command)

        backups = [b for b in process.stdout.split("\n") if b.startswith("databackup_") or b.startswith("log_backup_")]
        logger.info(f"List {len(backups)} required backup. {self._db_name} {target_time} {backups}")
        return backups

